<?php
namespace App\Http\Middleware;

use Closure;
use Illuminate\Http\Request;

/**
 * 跨域请求支持
 */
class AllowCorsDomain
{
    /**
     * 允许域名列表
     */
    protected $allow_domain = [];

    protected $header = [
        'Access-Control-Allow-Credentials' => 'true',
        'Access-Control-Max-Age'           => 1800,
        'Access-Control-Allow-Methods'     => 'GET, POST, PATCH, PUT, DELETE, OPTIONS',
        'Access-Control-Allow-Headers'     => 'Authorization, Content-Type, If-Match, If-Modified-Since, If-None-Match, If-Unmodified-Since, X-CSRF-TOKEN, X-Requested-With',
    ];

    public function __construct()
    {
        $this->allow_domain = config( 'user.allow_domain' );
    }

    /**
     * 允许跨域请求
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle( Request $request, Closure $next )
    {
        // 响应句柄
        $response = $next( $request );

        // 报头列表
        $header = $this->header;

        if ( ! isset( $header[ 'Access-Control-Allow-Origin' ] ) ) 
        {
            $origin = $request->header( 'origin' );
            if ( $origin && in_array( $origin, $this->allow_domain ) ) 
            {
                $header[ 'Access-Control-Allow-Origin' ] = $origin;
            }
            
            else
            {
                $header[ 'Access-Control-Allow-Origin' ] = '*';
            }
        }

        // 报头赋值
        foreach ( $header as $key => $value )
        {
            $response->header( $key, $value );
        }

        return $next( $request );
    }
}